//作者：向志祥
const express = require("express");
const db = require("../model/db");
const router = express.Router();
//添加
router.post("/", async (req, res) => {
    if (!req.body.screens) {
        req.body.screens = [];
    }
    const data = await db.MovieAndCinema.create(req.body);
    res.send({
        "code": 0,
        "msg": "",
        "data": data
    });
})
//获取上映电影
router.get("/", async (req, res) => {
    const data = await db.MovieAndCinema.find({ cinema: req.query.cid }).populate("cinema").populate("movie");
    res.send({
        "code": 0,
        "msg": "",
        "count": await db.MovieAndCinema.countDocuments({ cinema: req.query.cid }),
        "data": data
    });
})
//删除
router.delete("/:id", async (req, res) => {
    const data = await db.MovieAndCinema.deleteOne({
        _id: req.params.id
    })
    res.send({
        "code": 0,
        "msg": "",
        "data": data
    })
})
//获取未上映电影           $nin不在什么之中
router.get("/unused", async (req, res) => {
    let dis = await db.MovieAndCinema.find({
        cinema: req.query.cid
    }).select("-cinema -_id -screens -createTime -updateTime");

    const mid = dis.map(e => e.movie);
    let condition = {};
    if (req.query.key) {
        let exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询正则表达式
        condition = {
            _id: {
                $nin: mid
            },
            $or: [
                { name: { $regex: exp } },
                { type: { $regex: exp } }
            ]
        }
    } else {
        condition = {
            _id: {
                $nin: mid
            }
        }
    }
    let page = parseInt(req.query.page);
    let limit = parseInt(req.query.limit);
    if (!page) {
        page = 1;
    }
    if (!limit) {
        limit = 10
    }
    const data = await db.Movie.find(condition).skip((page - 1) * limit).limit(limit);
    res.send({
        code: 0,
        message: "",
        count: await db.Movie.countDocuments(condition),
        data
    });
})
//添加场次
router.put("/:id", async (req, res) => {
    const data = await db.MovieAndCinema.updateOne({
        _id: req.params.id
    }, {
            screens: req.body
        });
    res.send(data);
})
//获取场次
router.get("/:id", async (req, res) => {
    const data = await db.MovieAndCinema.findOne({ _id: req.params.id });
    res.send({
        "code": 0,
        "msg": "",
        "count": await db.MovieAndCinema.countDocuments({ _id: req.params.id }),
        "data": data
    });
})
module.exports = router;